package com.xywl.escort.view.withdraw

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.AddCashFlowReq
import com.xywl.escort.bean.BandCardListResp
import com.xywl.escort.bean.FindUserCashAmountResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.CashierInputFilter
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_withdraw.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import javax.inject.Inject

@Route(path = "/xy/withdraw")
class WithdrawActivity : BaseActivity(), WithdrawContract.View {
    private var bandBean: BandCardListResp.DataBean.ListBean? = null
    @Inject
    lateinit var mPresenter: WithdrawContract.Presenter

    private var mDataBean: FindUserCashAmountResp.DataBean? = null
    private val REQUEST_CODE_CHOOSE_BAND_CARD = 27

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_withdraw)
        showBackButton()
        setTitleText("提现")
        addListener()
        EventBus.getDefault().register(this)
    }

    override fun onResume() {
        super.onResume()
        mPresenter.takeView(this)
        val userId = RxSPTool.getString(this, USER_ID)
        mPresenter.findUserCashAmount(userId)
        mPresenter.getBandCardList("DC", 1, 1)
    }

    private fun addListener() {
        edit_price.filters = arrayOf<InputFilter>(CashierInputFilter())

        text_all_withdraw.setOnClickListener {
            if (null != mDataBean!!.accountFundsYuan) {
                val price = NumberFormatUtils.getInstance().format(mDataBean!!.accountFundsYuan.toDouble())
                edit_price.setText(price)
            }
        }

        btn_confirm.setOnClickListener {
            submit()
        }

        text_add_band_card.setOnClickListener {
            ARouter.getInstance().build("/xy/verify/pay/pwd")
                    .withString("path", "/xy/band/card/bind")
                    .navigation()
        }

//        text_band_name.setOnClickListener {
//            ARouter.getInstance()
//                    .build("/xy/band/card/dialog")
//                    .withObject("bandBean", bandBean)
//                    .navigation(this, REQUEST_CODE_CHOOSE_BAND_CARD)
//        }
    }

    private fun submit() {
        val price = edit_price.text.toString().trim()
        if (TextUtils.isEmpty(price)) {
            ToastUtil.showTip(this, "请输入提现金额")
            return
        }
        val doublePrice = price.toDouble()
        if (null != mDataBean!!.accountFundsYuan) {
            ToastUtil.showTip(this, "提现金额超过可提现金额")
            return
        }
        if (doublePrice > mDataBean!!.accountFundsYuan.toDouble()) {
            ToastUtil.showTip(this, "提现金额超过可提现金额")
            return
        }
        if (null == bandBean) {
            ToastUtil.showTip(this, "请选择提现银行卡")
            return
        }

        val bean = AddCashFlowReq()
        bean.userId = RxSPTool.getString(this, USER_ID)
        bean.cashFlowAmountYuan = price
        bean.bankcardId = bandBean!!.id
        bean.cashFlowChannel = 3
        ARouter.getInstance().build("/xy/verify/pay/pwd")
                .withInt("type", 1)
                .withObject("withdrawBean", bean)
                .navigation()
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("WithdrawActivity").e("event.message=" + event.message)
        Timber.tag("WithdrawActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_WITHDRAW_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.WITHDRAW_SUCCESS) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun getBandCardListSuccess(dataBean: BandCardListResp.DataBean?) {
        if (progress_bar.visibility == View.VISIBLE) {
            progress_bar.visibility = View.GONE
        }
        if (layout_content.visibility == View.GONE) {
            layout_content.visibility = View.VISIBLE
        }
        val list = dataBean!!.list
        if (list.size > 0) {
            if (text_add_band_card.visibility == View.VISIBLE) {
                text_add_band_card.visibility = View.GONE
            }
            if (text_band_name.visibility == View.GONE) {
                text_band_name.visibility = View.VISIBLE
            }
            bandBean = list[0]
            val item = list[0]
            var bankName = item.bankName
            val bankCardNo = item.bankCardNo
            if (bankCardNo.length > 4) {
                bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
            } else {
                bankName += " ($bankCardNo)"
            }
            text_band_name.text = bankName
        } else {
            Timber.e("list.size == 0")
            if (text_add_band_card.visibility == View.GONE) {
                text_add_band_card.visibility = View.VISIBLE
            }
            if (text_band_name.visibility == View.VISIBLE) {
                text_band_name.visibility = View.GONE
            }
        }
    }

    override fun getBandCardListFailure() {
        if (progress_bar.visibility == View.VISIBLE) {
            progress_bar.visibility = View.GONE
        }
        if (layout_content.visibility == View.GONE) {
            layout_content.visibility = View.VISIBLE
        }
        if (text_add_band_card.visibility == View.GONE) {
            text_add_band_card.visibility = View.VISIBLE
        }
        if (text_band_name.visibility == View.VISIBLE) {
            text_band_name.visibility = View.GONE
        }
        Timber.e("getBandCardListFailure")
    }

    override fun findUserCashAmountSuccess(dataBean: FindUserCashAmountResp.DataBean?) {
        mDataBean = dataBean
        if (progress_bar.visibility == View.VISIBLE) {
            progress_bar.visibility = View.GONE
        }
        if (layout_content.visibility == View.GONE) {
            layout_content.visibility = View.VISIBLE
        }
        if (null != dataBean!!.accountFundsYuan) {
            val canCarry = "可提现金额为￥" + NumberFormatUtils.getInstance().format(dataBean.accountFundsYuan.toDouble())
            text_can_carry.text = canCarry
        }
    }

    override fun findUserCashAmountFailure(msg: String?) {
        if (progress_bar.visibility == View.VISIBLE) {
            progress_bar.visibility = View.GONE
        }
        if (layout_content.visibility == View.GONE) {
            layout_content.visibility = View.VISIBLE
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CHOOSE_BAND_CARD -> {
                    data?.let {
                        bandBean = data.getSerializableExtra("bandBean") as BandCardListResp.DataBean.ListBean
                        Timber.tag("ProjectPayDialogActivity").e("bandBean.bankName=${bandBean!!.bankName}")
                        var bankName = bandBean!!.bankName
                        val bankCardNo = bandBean!!.bankCardNo
                        if (bankCardNo.length > 4) {
                            bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
                        } else {
                            bankName += " ($bankCardNo)"
                        }
                        text_band_card.text = bankName
                    }
                }
                else -> {
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
